package com.ibeeking.found.uaa.s.config.auth.token;

import com.ibeeking.found.common.constants.HeaderNounConstant;
import com.ibeeking.found.uaa.s.model.ShopUserDetails;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @ClassName JwtEnhanceConfig
 * @Description 往JWT中添加自定义信息
 * @Author ibeeking
 * @Date 2020-08-27 16:48
 **/
public class JwtEnhanceConfig extends JwtAccessTokenConverter {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        Map<String, Object> info = new LinkedHashMap<>();
        //添加租户id，用户id，用户名放入token
        if (authentication.getUserAuthentication().getPrincipal() instanceof ShopUserDetails) {
            ShopUserDetails shopUserDetails = (ShopUserDetails) authentication.getUserAuthentication().getPrincipal();
            info.put(HeaderNounConstant.USER_ID, String.valueOf(shopUserDetails.getId()));
            info.put(HeaderNounConstant.USER_NAME, shopUserDetails.getName());
            info.put(HeaderNounConstant.AM_DEMO_USER, shopUserDetails.isDemoUser());
            info.put(HeaderNounConstant.JUMP, shopUserDetails.isJump());
            if (shopUserDetails.isJump()) {
                info.put(HeaderNounConstant.TENANT_ID, shopUserDetails.getTenantId());
                info.put(HeaderNounConstant.INDUSTRY, shopUserDetails.getIndustry());
                info.put(HeaderNounConstant.SHOP_ID, shopUserDetails.getShopId());
            }
        }
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(info);
        return super.enhance(accessToken, authentication);
    }
}
